# 场景识别功能已注释，云侧不再进行场景识别
# 此文件包含场景识别相关的服务，已全部注释
# 场景记忆功能保留在 services/scene_memory.py 中

# from db.repository.scene import SceneRepository
# from sqlalchemy.orm import Session
# from typing import Dict, Any, Optional, List
# import json
# import time
# from utils.logger import (
#     emobot_logger,
#     log_function_call,
#     log_function_result,
#     log_function_error,
# )

# logger = emobot_logger.get_logger()


# class SceneService:
#     def __init__(self, db: Session):
#         self.db = db
#         self.scene_repo = SceneRepository(db)
#         logger.info("SceneService initialized")

#     def create_scene(
#         self, scene: str, platform: str, items: List[str]
#     ) -> Dict[str, Any]:
#         """创建新场景"""
#         start_time = time.time()
#         log_function_call(
#             "create_scene", {"scene": scene, "platform": platform, "items": items}
#         )

#         try:
#             # 验证输入
#             if not scene or not platform:
#                 raise ValueError("场景名称和平台位置不能为空")

#             if not isinstance(items, list):
#                 raise ValueError("物品必须是列表格式")

#             # 检查场景是否已存在
#             existing_scene = self.scene_repo.get_by_scene(scene)
#             if existing_scene:
#                 raise ValueError(f"场景 '{scene}' 已存在")

#             logger.info(f"Creating new scene: {scene} at {platform}")
#             scene_obj = self.scene_repo.create_scene(scene, platform, items)

#             result = {
#                 "id": str(scene_obj.id),
#                 "scene": scene_obj.scene,
#                 "platform": scene_obj.platform,
#                 "items": scene_obj.items,
#                 "created_at": scene_obj.created_at.isoformat()
#                 if scene_obj.created_at
#                 else "",
#                 "updated_at": scene_obj.updated_at.isoformat()
#                 if scene_obj.updated_at
#                 else "",
#             }

#             duration = (time.time() - start_time) * 1000
#             log_function_result("create_scene", result, duration)
#             logger.info(f"Scene created successfully: {scene}")

#             return result

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error(
#                 "create_scene", e, {"scene": scene, "platform": platform}
#             )
#             logger.error(f"Failed to create scene {scene}: {e}")
#             raise

#     def get_scene_by_id(self, scene_id: str) -> Optional[Dict[str, Any]]:
#         """根据ID获取场景"""
#         start_time = time.time()
#         log_function_call("get_scene_by_id", {"scene_id": scene_id})

#         try:
#             scene_obj = self.scene_repo.get(scene_id)
#             if scene_obj:
#                 result = {
#                     "id": str(scene_obj.id),
#                     "scene": scene_obj.scene,
#                     "platform": scene_obj.platform,
#                     "items": scene_obj.items,
#                     "created_at": scene_obj.created_at.isoformat()
#                     if scene_obj.created_at
#                     else "",
#                     "updated_at": scene_obj.updated_at.isoformat()
#                     if scene_obj.updated_at
#                     else "",
#                 }
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_id", result, duration)
#                 return result
#             else:
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_id", None, duration)
#                 return None

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_scene_by_id", e, {"scene_id": scene_id})
#             logger.error(f"Failed to get scene by ID {scene_id}: {e}")
#             raise

#     def get_scene_by_name(self, scene_name: str) -> Optional[Dict[str, Any]]:
#         """根据场景名称获取场景"""
#         start_time = time.time()
#         log_function_call("get_scene_by_name", {"scene_name": scene_name})

#         try:
#             scene_obj = self.scene_repo.get_by_scene(scene_name)
#             if scene_obj:
#                 result = {
#                     "id": str(scene_obj.id),
#                     "scene": scene_obj.scene,
#                     "platform": scene_obj.platform,
#                     "items": scene_obj.items,
#                     "created_at": scene_obj.created_at.isoformat()
#                     if scene_obj.created_at
#                     else "",
#                     "updated_at": scene_obj.updated_at.isoformat()
#                     if scene_obj.updated_at
#                     else "",
#                 }
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_name", result, duration)
#                 return result
#             else:
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_name", None, duration)
#                 return None

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_scene_by_name", e, {"scene_name": scene_name})
#             logger.error(f"Failed to get scene by name {scene_name}: {e}")
#             raise

#     def get_scene_by_name_and_platform(
#         self, scene_name: str, platform: str
#     ) -> Optional[Dict[str, Any]]:
#         """根据场景名称和平台位置获取场景"""
#         start_time = time.time()
#         log_function_call(
#             "get_scene_by_name_and_platform",
#             {"scene_name": scene_name, "platform": platform},
#         )

#         try:
#             scene_obj = self.scene_repo.get_by_scene_and_platform(scene_name, platform)
#             if scene_obj:
#                 result = {
#                     "id": str(scene_obj.id),
#                     "scene": scene_obj.scene,
#                     "platform": scene_obj.platform,
#                     "items": scene_obj.items,
#                     "created_at": scene_obj.created_at.isoformat()
#                     if scene_obj.created_at
#                     else "",
#                     "updated_at": scene_obj.updated_at.isoformat()
#                     if scene_obj.updated_at
#                     else "",
#                 }
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_name_and_platform", result, duration)
#                 return result
#             else:
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("get_scene_by_name_and_platform", None, duration)
#                 return None

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error(
#                 "get_scene_by_name_and_platform",
#                 e,
#                 {"scene_name": scene_name, "platform": platform},
#             )
#             logger.error(
#                 f"Failed to get scene by name {scene_name} and platform {platform}: {e}"
#             )
#             raise

#     def get_all_scenes(self) -> List[Dict[str, Any]]:
#         """获取所有场景"""
#         start_time = time.time()
#         log_function_call("get_all_scenes", {})

#         try:
#             scenes = self.scene_repo.get_all_scenes()
#             result = []
#             for scene_obj in scenes:
#                 result.append(
#                     {
#                         "id": str(scene_obj.id),
#                         "scene": scene_obj.scene,
#                         "platform": scene_obj.platform,
#                         "items": scene_obj.items,
#                         "created_at": scene_obj.created_at.isoformat()
#                         if scene_obj.created_at
#                         else "",
#                         "updated_at": scene_obj.updated_at.isoformat()
#                         if scene_obj.updated_at
#                         else "",
#                     }
#                 )

#             duration = (time.time() - start_time) * 1000
#             log_function_result("get_all_scenes", {"count": len(result)}, duration)
#             logger.info(f"Retrieved {len(result)} scenes")

#             return result

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_all_scenes", e, {})
#             logger.error(f"Failed to get all scenes: {e}")
#             raise

#     def update_scene(
#         self,
#         scene_id: str,
#         scene: str = None,
#         platform: str = None,
#         items: List[str] = None,
#     ) -> Optional[Dict[str, Any]]:
#         """更新场景"""
#         start_time = time.time()
#         log_function_call(
#             "update_scene",
#             {
#                 "scene_id": scene_id,
#                 "scene": scene,
#                 "platform": platform,
#                 "items": items,
#             },
#         )

#         try:
#             # 验证至少有一个更新字段
#             if scene is None and platform is None and items is None:
#                 raise ValueError("至少需要提供一个更新字段")

#             # 验证items格式
#             if items is not None and not isinstance(items, list):
#                 raise ValueError("物品必须是列表格式")

#             scene_obj = self.scene_repo.update_scene(scene_id, scene, platform, items)
#             if scene_obj:
#                 result = {
#                     "id": str(scene_obj.id),
#                     "scene": scene_obj.scene,
#                     "platform": scene_obj.platform,
#                     "items": scene_obj.items,
#                     "created_at": scene_obj.created_at.isoformat()
#                     if scene_obj.created_at
#                     else "",
#                     "updated_at": scene_obj.updated_at.isoformat()
#                     if scene_obj.updated_at
#                     else "",
#                 }
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("update_scene", result, duration)
#                 logger.info(f"Scene updated successfully: {scene_id}")
#                 return result
#             else:
#                 duration = (time.time() - start_time) * 1000
#                 log_function_result("update_scene", None, duration)
#                 logger.warning(f"Scene not found for update: {scene_id}")
#                 return None

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("update_scene", e, {"scene_id": scene_id})
#             logger.error(f"Failed to update scene {scene_id}: {e}")
#             raise

#     def delete_scene(self, scene_id: str) -> bool:
#         """删除场景"""
#         start_time = time.time()
#         log_function_call("delete_scene", {"scene_id": scene_id})

#         try:
#             success = self.scene_repo.delete_scene(scene_id)
#             duration = (time.time() - start_time) * 1000

#             if success:
#                 log_function_result("delete_scene", True, duration)
#                 logger.info(f"Scene deleted successfully: {scene_id}")
#             else:
#                 log_function_result("delete_scene", False, duration)
#                 logger.warning(f"Scene not found for deletion: {scene_id}")

#             return success

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("delete_scene", e, {"scene_id": scene_id})
#             logger.error(f"Failed to delete scene {scene_id}: {e}")
#             raise

#     def search_scenes(
#         self, scene_name: str = None, platform: str = None, item: str = None
#     ) -> List[Dict[str, Any]]:
#         """搜索场景"""
#         start_time = time.time()
#         log_function_call(
#             "search_scenes",
#             {"scene_name": scene_name, "platform": platform, "item": item},
#         )

#         try:
#             scenes = []

#             if scene_name:
#                 scenes = self.scene_repo.search_scenes_by_name(scene_name)
#             elif platform:
#                 scenes = self.scene_repo.get_by_platform(platform)
#             elif item:
#                 scenes = self.scene_repo.get_scenes_by_item(item)
#             else:
#                 scenes = self.scene_repo.get_all_scenes()

#             result = []
#             for scene_obj in scenes:
#                 result.append(
#                     {
#                         "id": str(scene_obj.id),
#                         "scene": scene_obj.scene,
#                         "platform": scene_obj.platform,
#                         "items": scene_obj.items,
#                         "created_at": scene_obj.created_at.isoformat()
#                         if scene_obj.created_at
#                         else "",
#                         "updated_at": scene_obj.updated_at.isoformat()
#                         if scene_obj.updated_at
#                         else "",
#                     }
#                 )

#             duration = (time.time() - start_time) * 1000
#             log_function_result("search_scenes", {"count": len(result)}, duration)
#             logger.info(f"Scene search returned {len(result)} results")

#             return result

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error(
#                 "search_scenes",
#                 e,
#                 {"scene_name": scene_name, "platform": platform, "item": item},
#             )
#             logger.error(f"Failed to search scenes: {e}")
#             raise

#     def get_scene_statistics(self) -> Dict[str, Any]:
#         """获取场景统计信息"""
#         start_time = time.time()
#         log_function_call("get_scene_statistics", {})

#         try:
#             stats = self.scene_repo.get_scene_statistics()
#             duration = (time.time() - start_time) * 1000
#             log_function_result("get_scene_statistics", stats, duration)
#             logger.info("Scene statistics retrieved successfully")
#             return stats

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_scene_statistics", e, {})
#             logger.error(f"Failed to get scene statistics: {e}")
#             raise

#     def get_unique_platforms(self) -> List[str]:
#         """获取所有唯一的平台位置"""
#         start_time = time.time()
#         log_function_call("get_unique_platforms", {})

#         try:
#             platforms = self.scene_repo.get_unique_platforms()
#             duration = (time.time() - start_time) * 1000
#             log_function_result("get_unique_platforms", platforms, duration)
#             return platforms

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_unique_platforms", e, {})
#             logger.error(f"Failed to get unique platforms: {e}")
#             raise

#     def get_unique_items(self) -> List[str]:
#         """获取所有唯一的物品"""
#         start_time = time.time()
#         log_function_call("get_unique_items", {})

#         try:
#             items = self.scene_repo.get_unique_items()
#             duration = (time.time() - start_time) * 1000
#             log_function_result("get_unique_items", items, duration)
#             return items

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("get_unique_items", e, {})
#             logger.error(f"Failed to get unique items: {e}")
#             raise

#     def bulk_create_scenes(
#         self, scenes_data: List[Dict[str, Any]]
#     ) -> List[Dict[str, Any]]:
#         """批量创建场景"""
#         start_time = time.time()
#         log_function_call("bulk_create_scenes", {"count": len(scenes_data)})

#         try:
#             # 验证数据格式
#             for i, scene_data in enumerate(scenes_data):
#                 if not all(key in scene_data for key in ["scene", "platform", "items"]):
#                     raise ValueError(f"第 {i+1} 个场景数据缺少必要字段")
#                 if not isinstance(scene_data["items"], list):
#                     raise ValueError(f"第 {i+1} 个场景的items字段必须是列表格式")

#             scene_objs = self.scene_repo.bulk_create_scenes(scenes_data)
#             result = []
#             for scene_obj in scene_objs:
#                 result.append(
#                     {
#                         "id": str(scene_obj.id),
#                         "scene": scene_obj.scene,
#                         "platform": scene_obj.platform,
#                         "items": scene_obj.items,
#                         "created_at": scene_obj.created_at.isoformat()
#                         if scene_obj.created_at
#                         else "",
#                         "updated_at": scene_obj.updated_at.isoformat()
#                         if scene_obj.updated_at
#                         else "",
#                     }
#                 )

#             duration = (time.time() - start_time) * 1000
#             log_function_result("bulk_create_scenes", {"count": len(result)}, duration)
#             logger.info(f"Bulk created {len(result)} scenes")

#             return result

#         except Exception as e:
#             duration = (time.time() - start_time) * 1000
#             log_function_error("bulk_create_scenes", e, {"count": len(scenes_data)})
#             logger.error(f"Failed to bulk create scenes: {e}")
#             raise